//
//  MainTabBarController.swift
//  SinaWeiBo
//
//  Created by Leon 笑 竹 on 2017/7/31.
//  Copyright © 2017年 Leon 笑 竹. All rights reserved.
//

import UIKit

class MainTabBarController: UITabBarController {
    
    //设置定时器（两种，一种是timer，一种是GCDtimer）
    //1.Timer
    fileprivate var timer : Timer?
    
    //2.GCDtimer
    
    //按钮懒加载属性(中间按钮)
    fileprivate lazy var compseBtn : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    

    override func viewDidLoad() {
        super.viewDidLoad()

        //添加自控制器
        setupAllChildController()
        addComposeBtn()
        
        //设置定时器
        setupTimer()
        
        //设置代理
        delegate = self
        
    }
    
    //销毁timer
    deinit {
        timer?.invalidate()
    }
    
    //控制设备横竖屏
    /// protrait :竖屏
    /// landscape : 横屏
    /// 只有他和他的自控制器才遵守
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return.portrait
    }
    
    //点击中间按钮
   @objc fileprivate func clickMidBtn() {
        print("点击了中间的按钮")
    
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let navi = UINavigationController(rootViewController: vc)
        self.present(navi, animated: true, completion: nil)
    }
}

//UITabBarDelegate
extension MainTabBarController : UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        
        let index = childViewControllers.index(of: viewController)
        
        //判断当前页是否是首页
        if  selectedIndex == 0 && index == selectedIndex {
            print("选择了首页")
            
            //获取到控制器
            let vc = (childViewControllers[0] as! UINavigationController).childViewControllers[0] as! HomeViewController
            
            //滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x : 0 , y: -64), animated: true)
            
            //刷新数据
            //延迟一秒钟刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
            //清除tabbar的badge
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
//        print("将要切换到 \(viewController)")
        //这个方法就是如果不是viewController就切换，如果是就不切换，避免了容错点
        return !viewController.isMember(of: UIViewController.self)
        
    }
}


//设置定时器
extension MainTabBarController {
    
    //1.timer
    
    fileprivate func setupTimer(){
        
        //定时器任务
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc fileprivate func updateTimer() {
        
//        print(#function)
        
        if NetworkManager.shared.access_Token == nil{
            return
        }
        
        //消息未读数量测试
        NetworkManager.shared.unreadCount { (count) in
            print("微博的未读数量是 \(count)")
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置app的未读数量
            
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

//相当于一个扩展
extension MainTabBarController {
    
    fileprivate func addComposeBtn() {
        
        tabBar.addSubview(compseBtn)
        
        //设置按钮位置
        let count = childViewControllers.count
        //容错点
        let w = tabBar.bounds.width / CGFloat(count)
        //添加中间按钮的尺寸
        compseBtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //添加中间按钮的点击行为
        compseBtn.addTarget(self, action: #selector(clickMidBtn), for: .touchUpInside)
    }
    
    
    fileprivate func setupAllChildController() {
        
//        //读取json文件
        //从plist 读取
//        guard let json = Bundle.main.path(forResource: "main.plist", ofType: nil),
//        let array = NSArray(contentsOfFile:json) as? [[String : AnyObject]] else {
//            return
//        }
        
        //从沙盒路径读取文件
        //path
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        //append
        let jsonPath = (path as NSString).appendingPathComponent("main.json")
        
        //转换成data
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            //加载本地文件
            let path = Bundle.main.path(forResource: "demo.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        //从json读取
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : AnyObject]]
            else {
            return
        }
        
        //生成控制器数组
//        let array = [
//            //首页
//            ["clsName" : "HomeViewController","title" :"首页","imageName" : "tabbar_home","selectedImageName" : "tabbar_home_selected",
//            
//                "visitorInfo" : ["imageName" : "" , "message" : "关注一些人，回这里看看有什么惊喜"]
//            
//            ],
//            //消息
//            ["clsName" : "MessageController","title" :"消息","imageName" : "tabbar_message_center","selectedImageName" : "tabbar_message_center_selected",
//            
//                 "visitorInfo" : ["imageName" : "visitordiscover_image_message" , "message" : "登录后，别人评论你的微博，发给你消息，都会在这里收到通知"]
//            ],
//            //中间的加号按钮站位
//            ["clsName":"UIViewController"],
//            //发现
//            ["clsName" : "DiscoverController","title" :"发现","imageName" : "tabbar_discover","selectedImageName" : "tabbar_discover_selected",
//            
//                 "visitorInfo" : ["imageName" : "visitordiscover_image_message" , "message" : "登录后，最新最热微博尽在掌握，不会再与事实潮流擦肩而过"]
//            ],
//            //我的
//            ["clsName" : "ProfileController","title" :"我的","imageName" : "tabbar_profile","selectedImageName" : "tabbar_profile_selected",
//             
//                 "visitorInfo" : ["imageName" : "visitordiscover_image_profile" , "message" : "登录后，你的微博，相册，个人资料都会显示在这里，展示给别人"]
//             ]
//                        ]
//        
//        //写成plist,测试格式是否正确
//        (array as NSArray).write(toFile: "/Users/Leon/Desktop/main.plist", atomically: true);
        
//        //序列化数组
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/Leon/Desktop/demo.json", atomically: true)
        
        //创建一个控制器数组
        var arrayM = [UIViewController]()
        //遍历数组里的内容
        for dict in array! {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        //Tabbar子控制器添加
        viewControllers = arrayM
    }
    
    fileprivate func controller(dict : [String : AnyObject]) -> UIViewController{
        //当这四个值没有内容返回空的控制器
        guard let clsName = dict["clsName"] as? String,
                  let title = dict["title"] as? String,
                  let imageName = dict["imageName"] as? String,
                  let selectedImageName = dict["selectedImageName"] as? String,
            //工厂模式(反射机制)
                  let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? BaseViewController.Type,
                  let visitorInfo = dict["visitorInfo"] as? [String: String]
        else {
                    return UIViewController()
        }
        
        //创建控制器
        let vc = cls.init()

        vc.visitorInfoDict = visitorInfo
        //标题
        vc.title = title
        //导航
        let navi = MainNaviController(rootViewController: vc)
        //图标
        navi.tabBarItem.image = UIImage.init(named: imageName)
        //选择图标
        navi.tabBarItem.selectedImage = UIImage.init(named: selectedImageName)?.withRenderingMode(.alwaysOriginal)
        
        //设置tabbar的颜色和字体，用属性字典
        navi.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName : UIColor.orange], for: .selected)
        //多态返回
        return navi
    }
}
